package com.example.otherapp.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;

import java.util.Map;

@RestController
public class AuthorityController {
    @Value(value = "${zhangpingyang.oauth.token.url}")
    private String tokenUrl;
    @Value(value = "${zhangpingyang.clientId}")
    private String clientId;
    @Value(value = "${zhangpingyang.clientsecret}")
    private String clientSecret;
    @Value(value = "${zhangpingyang.username}")
    private String username;
    @Value(value = "${zhangpingyang.password}")
    private String password;
    @Value(value = "${zhangpingyang.scope}")
    private String scope;
    @Value(value = "${zhangpingyang.grant_type}")
    private String grant_type;
//    BASE64Encoder encoder = new BASE64Encoder();
    private RestTemplate restTemplate = new RestTemplate();
    @GetMapping("authenticateByPassword")
    public Map authenticate() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.setBasicAuth(clientId, clientSecret);
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        map.add("username", username);
        map.add("password", password);
        map.add("scope", scope);
        map.add("grant_type", grant_type);

        HttpEntity httpEntity = new HttpEntity(map, headers);
        Map map1 = restTemplate.postForObject(tokenUrl+"/oauth/token", httpEntity, Map.class);
        return map1;
    }
}
